
import config from '@/config/global.js'

import { computePublicKey } from "@ethersproject/signing-key"
import { ethToLAMBDA } from '@webfans/address-converter'
import { utils } from "ethers"
import Web3 from 'web3'

require('isomorphic-fetch')


export async function getCachedPublicKey(account_eth){
    const rest = config.RestAPI
    let account_cosmos = ethToLAMBDA(account_eth)
    let url =`${rest}/cosmos/auth/v1beta1/accounts/${account_cosmos}`

    let data
    try {
        let res = await fetch(url);
        data = await res.json()    
    } catch (error) {
    }

    //get pubkey if account has transaction
    if(data&&data.account.base_account.pub_key&&data.account.base_account.pub_key.key){
        return data.account.base_account.pub_key.key;
    }
}

export async function getPublicKeyWithSig(account_eth){
    try{
        //get from signature
        var nounce = new Date().getTime()
        let message = `Welcome to Lambda! \n\nClick "Sign" to sign in. No password needed! \n\nAddress:${account_eth} \n\nNonce: ${nounce}`
        let web3 = new Web3(window.ethereum)
        const signature = await web3.eth.personal.sign(message,account_eth)
        const msgHash = utils.hashMessage(message);
        const msgHashBytes = utils.arrayify(msgHash);
        const recoveredPubKey = utils.recoverPublicKey(msgHashBytes, signature);
        let PublicKey =   computePublicKey(recoveredPubKey,true);    
        let PublicKeyStr= PublicKey.substring(2)
        let B1 = Buffer.from(PublicKeyStr,'hex')
        let PublicKeyBase64 = B1.toString('base64');
        return PublicKeyBase64;
    }catch(e){
        console.log(e)
        return null
    }
}